#!/usr/bin/env python3
"""
ComfyUI BuimenLabo - Cross-platform Installation Script
Ensures reliable installation across Windows, macOS, and Linux
"""

import subprocess
import sys
import os
import platform
from pathlib import Path

def run_command(command, description, ignore_error=False):
    """Run a command with error handling."""
    print(f"🔄 {description}...")
    try:
        result = subprocess.run(command, shell=True, check=True, 
                              capture_output=True, text=True)
        print(f"✅ {description} completed")
        return True
    except subprocess.CalledProcessError as e:
        if ignore_error:
            print(f"⚠️ {description} failed (continuing): {e}")
            return False
        else:
            print(f"❌ {description} failed: {e}")
            if e.stdout:
                print(f"stdout: {e.stdout}")
            if e.stderr:
                print(f"stderr: {e.stderr}")
            return False

def main():
    print("=" * 50)
    print("🚀 ComfyUI BuimenLabo - Installation Script")
    print("📝 Blog: https://note.com/hirodream44")
    print("=" * 50)
    print()

    # Get Python executable
    python_cmd = sys.executable
    
    print(f"🐍 Using Python: {python_cmd}")
    print(f"🖥️ Platform: {platform.system()} {platform.release()}")
    print()

    # Install core dependencies
    core_deps = [
        "requests>=2.28.0",
        "numpy>=1.21.0", 
        "Pillow>=9.0.0",
        "psutil>=5.9.0"
    ]
    
    print("📦 Installing core dependencies...")
    for dep in core_deps:
        cmd = f'"{python_cmd}" -m pip install "{dep}"'
        if not run_command(cmd, f"Installing {dep}", ignore_error=True):
            print(f"⚠️ {dep} may already be installed or will be handled by ComfyUI")
    
    # Install Gemini API support
    print("\n🤖 Installing Gemini API support...")
    gemini_cmd = f'"{python_cmd}" -m pip install "google-generativeai>=0.3.0"'
    if not run_command(gemini_cmd, "Installing google-generativeai", ignore_error=True):
        print("⚠️ Google Generative AI installation failed")
        print("   You can install manually: pip install google-generativeai")

    # Llama-cpp-python information
    print("\n🦙 Llama-CPP Python Setup Information:")
    print("   ⚠️ llama-cpp-python requires hardware-specific installation")
    print("   🔧 For optimal performance:")
    print()
    print("   🖥️  CPU only:")
    print(f'      "{python_cmd}" -m pip install llama-cpp-python')
    print()
    print("   🎮 NVIDIA GPU (CUDA):")
    print('      set CMAKE_ARGS="-DGGML_CUDA=on"')
    print(f'      "{python_cmd}" -m pip install llama-cpp-python --force-reinstall --no-cache-dir')
    print()
    print("   🍎 Apple Silicon (Metal):")
    print('      export CMAKE_ARGS="-DGGML_METAL=on"')
    print(f'      "{python_cmd}" -m pip install llama-cpp-python --force-reinstall --no-cache-dir')
    print()
    print("   🔴 AMD GPU (ROCm):")
    print('      export CMAKE_ARGS="-DGGML_ROCM=on"')
    print(f'      "{python_cmd}" -m pip install llama-cpp-python --force-reinstall --no-cache-dir')
    print()

    # Platform-specific instructions
    if platform.system() == "Windows":
        print("💡 Windows users: Run install.bat for interactive installation")
    
    print("=" * 50)
    print("✅ Core installation completed!")
    print("=" * 50)
    print()
    print("📋 Next steps:")
    print("   1. Restart ComfyUI")
    print("   2. Look for BuimenLabo nodes in Add Node menu")
    print("   3. For LLM: Download GGUF models to ComfyUI/models/llm/")
    print("   4. For Gemini: Get API key from https://makersuite.google.com/app/apikey")
    print("   5. Check language toggle (🌐) in top-right corner")
    print()
    print("🆘 Troubleshooting:")
    print("   • Language toggle missing → Refresh browser (F5)")
    print("   • VRAM issues → Lower GPU layers in LLM nodes")
    print("   • API errors → Check internet and API keys")
    print()
    print("📝 Documentation: https://github.com/comnote-max/builmenlabo")
    print("📖 Blog: https://note.com/hirodream44")

if __name__ == "__main__":
    main()